// === 配置区 ===
const API_KEY = 'live_hysCJUH4tsryYS5eCT5QmfLpolwqUDNO7hMBk61Fl9jVKpSwpKSLJ4ijDAIdhoaC';
const API_BASE_URL = 'https://api.thecatapi.com/v1/images/search';

// === API配置 ===
const BASE_API_URL = 'http://localhost:8080/api';
const USER_API_URL = `${BASE_API_URL}/user`;
const LIKE_API_URL = `${BASE_API_URL}/likes`;

// === 获取DOM元素 ===
const getCatButton = document.getElementById('get-cat');
const catContainer = document.getElementById('cat-container');
const myLikesContainer = document.getElementById('my-likes-container');
const loadingText = document.getElementById('loading-text');
const userInfo = document.getElementById('user-info');
const welcomeMessage = document.getElementById('welcome-message');
const logoutButton = document.getElementById('logout-button');
const myLikesButton = document.getElementById('my-likes-button');

// === 状态管理 ===
let currentUser = null;
let currentView = 'random'; // 'random' 或 'likes'

// === 检查登录状态，如果未登录则重定向到登录页面 ===
function checkLoginStatus() {
    const savedUser = localStorage.getItem('currentUser');
    if (!savedUser) {
        window.location.href = 'index.html';
        return false;
    }
    currentUser = savedUser;
    return true;
}

// === 主要函数：获取随机猫咪图片 ===
async function getRandomCats() {
    // 确保显示随机猫咪容器，隐藏喜欢猫咪容器
    setView('random');
    
    // 1. 显示加载状态，清空容器
    loadingText.textContent = '正在寻找可爱的小猫咪们...';
    catContainer.innerHTML = '';

    try {
        // 生成随机数量（3-5张）
        const count = Math.floor(Math.random() * 3) + 3;
        
        // 2. 发起API请求，添加limit参数
        const response = await fetch(`${API_BASE_URL}?limit=${count}`, {
            headers: {
                'x-api-key': API_KEY
            }
        });

        // 3. 检查请求是否成功
        if (!response.ok) {
            throw new Error(`网络响应不正常: ${response.status}`);
        }

        // 4. 解析JSON数据
        const data = await response.json();

        // 5. 逐个加载图片并立即显示，而不是等待全部加载
        let imagesLoaded = 0;
        const totalImages = data.length;
        
        data.forEach(catData => {
            loadImage(catData.url, catContainer, false).then(img => {
                const card = img.parentElement;
                card.style.display = 'block';
                imagesLoaded++;
                
                // 当第一张图片加载完成后就隐藏加载文字
                if (imagesLoaded === 1) {
                    loadingText.textContent = '';
                }
            }).catch(error => {
                console.error('加载单张图片失败:', error);
                imagesLoaded++;
                if (imagesLoaded === totalImages) {
                    loadingText.textContent = '';
                }
            });
        });

    } catch (error) {
        // 9. 错误处理
        console.error('获取猫咪失败:', error);
        loadingText.textContent = '抱歉，猫咪们走丢了... 请稍后再试。';
        loadingText.style.color = 'red';
    }
}

// === 辅助函数：创建并加载图片 ===
function loadImage(url, container, isFromLikes = false, maxRetries = 2, timeout = 5000) {
    // 预加载图片
    const preloadImg = new Image();
    
    return new Promise((resolve, reject) => {
        // 创建图片卡片
        const card = document.createElement('div');
        card.className = 'cat-card';
        
        // 添加骨架屏效果
        const skeleton = document.createElement('div');
        skeleton.className = 'skeleton';
        skeleton.style.width = '200px';
        skeleton.style.height = '200px';
        skeleton.style.backgroundColor = '#f0f0f0';
        skeleton.style.borderRadius = '8px';
        skeleton.style.animation = 'pulse 1.5s infinite';
        card.appendChild(skeleton);
        
        // 创建图片元素
        const img = document.createElement('img');
        img.className = 'cat-image';
        img.alt = '一张可爱的随机猫咪图片';
        img.style.opacity = '0'; // 初始设置为透明，添加淡入效果
        img.style.transition = 'opacity 0.3s ease-in-out';
        
        // 如果是已登录用户，添加点赞按钮
        if (currentUser) {
            const likeButton = document.createElement('button');
            likeButton.className = 'like-button';
            likeButton.innerHTML = '🤍';
            likeButton.dataset.url = url;
            
            // 异步检查点赞状态
            checkLikeStatus(url).then(isLiked => {
                if (isLiked) {
                    likeButton.classList.add('liked');
                    likeButton.innerHTML = '❤️';
                }
            }).catch(error => {
                console.error('检查点赞状态失败:', error);
            });
            
            // 添加点赞事件
            likeButton.addEventListener('click', (e) => {
                e.stopPropagation();
                toggleLike(url, likeButton);
            });
            
            card.appendChild(likeButton);
        }
        
        // 添加到容器
        card.appendChild(img);
        container.appendChild(card);
        
        let retries = 0;
        let timeoutId;
        
        function attemptLoad() {
            // 清除之前的超时
            if (timeoutId) clearTimeout(timeoutId);
            
            // 设置新的超时
            timeoutId = setTimeout(() => {
                retries++;
                if (retries <= maxRetries) {
                    console.warn(`图片加载超时，正在进行第 ${retries} 次重试: ${url}`);
                    attemptLoad();
                } else {
                    reject(new Error(`图片加载超时，已重试 ${maxRetries} 次: ${url}`));
                }
            }, timeout);
            
            // 开始加载图片
            preloadImg.onload = () => {
                clearTimeout(timeoutId);
                // 图片加载完成后，显示图片并隐藏骨架屏
                skeleton.remove();
                img.src = url; // 设置实际图片源
                img.onload = () => {
                    // 添加淡入效果
                    setTimeout(() => {
                        img.style.opacity = '1';
                        resolve(img);
                    }, 50);
                };
                img.onerror = () => {
                    retries++;
                    if (retries <= maxRetries) {
                        console.warn(`图片加载失败，正在进行第 ${retries} 次重试: ${url}`);
                        attemptLoad();
                    } else {
                        reject(new Error(`图片加载失败，已重试 ${maxRetries} 次: ${url}`));
                    }
                };
            };
            
            preloadImg.onerror = () => {
                clearTimeout(timeoutId);
                retries++;
                if (retries <= maxRetries) {
                    console.warn(`预加载失败，正在进行第 ${retries} 次重试: ${url}`);
                    attemptLoad();
                } else {
                    reject(new Error(`预加载失败，已重试 ${maxRetries} 次: ${url}`));
                }
            };
            
            // 开始预加载
            preloadImg.src = url;
        }
        
        // 开始第一次加载尝试
        attemptLoad();
    });
}

// === 登录功能 ===
async function login() {
    const username = usernameInput.value;
    const password = passwordInput.value;
    
    try {
        // 向后端发送登录请求
        const response = await fetch(`${USER_API_URL}/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 登录成功
            currentUser = username;
            localStorage.setItem('currentUser', username);
            
            // 更新UI
            loginForm.classList.add('hidden');
            userInfo.classList.remove('hidden');
            welcomeMessage.textContent = `欢迎，${username}！`;
            
            // 如果当前有猫咪图片，为它们添加点赞按钮
            addLikeButtonsToExistingCards();
            
            // 如果已经登录，自动获取猫咪
            if (currentView === 'random' && catContainer.children.length === 0) {
                getRandomCats();
            }
        } else {
            alert('用户名或密码错误！请使用初始账号：admin，密码：123456');
        }
    } catch (error) {
        console.error('登录失败:', error);
        // 如果后端API不可用，使用本地验证作为备选方案
        fallbackLogin(username, password);
    }
}

// === 备用登录方案（当后端不可用时）=== 
function fallbackLogin(username, password) {
    if (username === 'admin' && password === '123456') {
        // 登录成功
        currentUser = username;
        localStorage.setItem('currentUser', username);
        
        // 更新UI
        loginForm.classList.add('hidden');
        userInfo.classList.remove('hidden');
        welcomeMessage.textContent = `欢迎，${username}！`;
        
        // 如果当前有猫咪图片，为它们添加点赞按钮
        addLikeButtonsToExistingCards();
        
        // 如果已经登录，自动获取猫咪
        if (currentView === 'random' && catContainer.children.length === 0) {
            getRandomCats();
        }
    } else {
        alert('用户名或密码错误！请使用初始账号：admin，密码：123456');
    }
}

// === 登出功能 ===
function logout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    
    // 重定向到登录页面（index.html就是登录页面）
    window.location.href = 'index.html';
}

// === 切换点赞状态 ===
async function toggleLike(url, button) {
    if (!currentUser) {
        alert('请先登录才能点赞！');
        return;
    }
    
    try {
        const isLiked = button.classList.contains('liked');
        
        if (isLiked) {
            // 取消点赞
            const success = await cancelLike(url);
            if (success) {
                button.classList.remove('liked');
                button.innerHTML = '🤍';
            }
        } else {
            // 点赞
            const success = await addLike(url);
            if (success) {
                button.classList.add('liked');
                button.innerHTML = '❤️';
            }
        }
    } catch (error) {
        console.error('切换点赞状态失败:', error);
        alert('操作失败，请稍后再试！');
    }
}

// === 检查点赞状态 ===
async function checkLikeStatus(url) {
    try {
        const response = await fetch(`${LIKE_API_URL}/check?username=${currentUser}&catUrl=${encodeURIComponent(url)}`);
        if (response.ok) {
            const isLiked = await response.json();
            return isLiked;
        }
    } catch (error) {
        console.error('检查点赞状态失败:', error);
    }
    return false;
}

// === 添加点赞到后端 ===
async function addLike(url) {
    try {
        const response = await fetch(`${LIKE_API_URL}?username=${currentUser}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ catUrl: url })
        });
        
        if (!response.ok) {
            throw new Error('添加点赞失败');
        }
        return true;
    } catch (error) {
        console.error('向后端添加点赞失败:', error);
        throw error;
    }
}

// === 从后端取消点赞 ===
async function cancelLike(url) {
    try {
        const response = await fetch(`${LIKE_API_URL}?username=${currentUser}&catUrl=${encodeURIComponent(url)}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error('取消点赞失败');
        }
        return true;
    } catch (error) {
        console.error('向后端取消点赞失败:', error);
        throw error;
    }
}

// === 获取已点赞的猫咪列表（从数据库） ===
async function getLikedCats() {
    if (!currentUser) return [];
    
    try {
        const response = await fetch(`${LIKE_API_URL}?username=${currentUser}`);
        if (response.ok) {
            const data = await response.json();
            return data || [];
        }
    } catch (error) {
        console.error('获取点赞列表失败:', error);
    }
    return [];
}

// === 从后端获取已点赞的猫咪列表 ===
async function fetchLikedCats(username) {
    try {
        const response = await fetch(`${LIKE_API_URL}?username=${username}`);
        if (response.ok) {
            const data = await response.json();
            return data || [];
        }
    } catch (error) {
        console.error('从后端获取点赞列表失败:', error);
    }
    return [];
}

// === 显示我的喜欢 ===
async function showMyLikes() {
    // 确保用户已登录
    if (!currentUser) {
        alert('请先登录才能查看您喜欢的猫咪！');
        return;
    }
    
    setView('likes');
    
    // 清空容器
    myLikesContainer.innerHTML = '';
    loadingText.textContent = '正在加载您喜欢的猫咪...';
    
    try {
        // 从后端获取最新的点赞列表
        const likedCats = await fetchLikedCats(currentUser);
        
        if (!likedCats || likedCats.length === 0) {
            loadingText.textContent = '您还没有喜欢任何猫咪哦！';
            return;
        }
        
        // 逐个加载图片并立即显示，而不是等待全部加载
        let imagesLoaded = 0;
        const totalImages = likedCats.length;
        
        likedCats.forEach(url => {
            loadImage(url, myLikesContainer, true).then(img => {
                const card = img.parentElement;
                card.style.display = 'block';
                imagesLoaded++;
                
                // 当第一张图片加载完成后就隐藏加载文字
                if (imagesLoaded === 1) {
                    loadingText.textContent = '';
                }
            }).catch(error => {
                console.error('加载单张图片失败:', error);
                imagesLoaded++;
                if (imagesLoaded === totalImages) {
                    loadingText.textContent = '';
                }
            });
        });
    } catch (error) {
        console.error('加载喜欢的猫咪失败:', error);
        loadingText.textContent = '加载失败，请稍后再试。';
        loadingText.style.color = 'red';
    }
}

// === 设置当前视图 ===
function setView(view) {
    currentView = view;
    
    if (view === 'random') {
        catContainer.classList.remove('hidden');
        myLikesContainer.classList.add('hidden');
    } else if (view === 'likes') {
        catContainer.classList.add('hidden');
        myLikesContainer.classList.remove('hidden');
    }
}

// === 为已存在的卡片添加点赞按钮 ===
async function addLikeButtonsToExistingCards() {
    const cards = catContainer.querySelectorAll('.cat-card');
    const likedCats = await getLikedCats();
    
    cards.forEach(card => {
        // 检查是否已经有点赞按钮
        if (card.querySelector('.like-button')) return;
        
        const img = card.querySelector('.cat-image');
        const url = img.src;
        
        const likeButton = document.createElement('button');
        likeButton.className = 'like-button';
        likeButton.innerHTML = '🤍';
        likeButton.dataset.url = url;
        
        // 检查是否已点赞
        if (likedCats.includes(url)) {
            likeButton.classList.add('liked');
            likeButton.innerHTML = '❤️';
        }
        
        // 添加点赞事件
        likeButton.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleLike(url, likeButton);
        });
        
        card.appendChild(likeButton);
    });
}

// === 移除所有点赞按钮 ===
function removeLikeButtons() {
    const likeButtons = document.querySelectorAll('.like-button');
    likeButtons.forEach(button => {
        button.remove();
    });
}

// === 初始化 ===
async function init() {
    // 检查登录状态
    if (!checkLoginStatus()) {
        return;
    }
    
    try {
        // 验证用户是否有效
        const response = await fetch(`${USER_API_URL}/validate?username=${currentUser}`);
        const data = await response.json();
        
        if (data.valid) {
            welcomeMessage.textContent = `欢迎，${currentUser}！`;
        } else {
            // 用户验证失败，清除本地存储并重定向
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
            return;
        }
    } catch (error) {
        console.error('验证用户失败:', error);
        // 后端不可用时，直接显示欢迎信息
        welcomeMessage.textContent = `欢迎，${currentUser}！`;
    }
    
    // 如果没有猫咪图片，自动获取猫咪
    if (currentView === 'random' && catContainer.children.length === 0) {
        getRandomCats();
    }
}

// === 事件监听 ===
// 点击按钮时获取新猫咪
getCatButton.addEventListener('click', getRandomCats);

// 登出按钮事件
logoutButton.addEventListener('click', logout);

// 我的喜欢按钮事件
myLikesButton.addEventListener('click', showMyLikes);

// 页面加载时初始化
window.onload = init;